package com.example.mystore.service.impl;

import com.example.mystore.model.Address;
import com.example.mystore.mapper.AddressMapper;
import com.example.mystore.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    @Override
    public List<Address> getAddressesByUserId(Integer userId) {
        return addressMapper.findAddressesByUserId(userId);
    }

    @Override
    public List<Address> list(Integer id) {
        return addressMapper.selectAllAddresses(id);
    }

    @Override
    public int save(Address address) {
        address.setCreated(new Date());
        address.setUpdated(new Date());
        address.setDfault(0);
        address.setIsDel(0);
        return addressMapper.insertAddress(address);
    }

    @Override
    public int update(Address address) {
        address.setUpdated(new Date());
        address.setDfault(addressMapper.getAddressById(address.getId()).getDfault());
        return addressMapper.updateAddress(address);
    }

    @Override
    public int delete(Integer id) {
        return addressMapper.deleteAddressById(id);
    }

    @Override
    public Integer setDefault(Integer id) {
        List<Address> addresses = addressMapper.selectAllAddresses(1);
        for (Address address : addresses) {
            address.setDfault(0);
            addressMapper.updateAddress(address);
        }
        Address addressById = addressMapper.getAddressById(id);
        addressById.setDfault(1);
        addressById.setUpdated(new Date());
        addressMapper.updateAddress(addressById);
        return null;
    }

    @Override
    public Address get(Integer id) {
        return addressMapper.getAddressById(id);
    }

}
